package com.qasystem.qa.core.Intercepter;

import com.qasystem.qa.core.constants.Constants;
import com.qasystem.qa.core.service.RedisService;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

public class AuthIntercepter implements HandlerInterceptor {
    @Autowired
    private RedisService redisService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        //String token = request.getHeader("token");
        boolean cookieHave = false;
        Cookie[] cookies = request.getCookies();
        if ((cookies != null)) {
            for (Cookie cookie : cookies) {
                System.out.println(cookie.getName());
                if (cookie.getName().equals(Constants.COOKIE_NAME) && redisService.get(cookie.getValue()) != null) {
                    cookieHave = true;
                    return true;
                }
            }
        }
        if (!cookieHave) {
            System.out.println("request.getContextPath: " + request.getContextPath());
            response.sendRedirect(request.getContextPath() + "/login");
            //response.getWriter().print("用户未登陆");
            return false;
        }
//        Object loginStatus =redisService.get(token);
//        if (!Objects.isNull(loginStatus)) {
//            response.getWriter().print("token错误，请查看！");
//            return false;
//        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
